package com.gaofans.vertx.boot.web.csrf;

import com.gaofans.vertx.boot.web.route.RouterExtConfigurer;
import com.gaofans.vertx.boot.web.utils.HttpHandlerOrder;
import com.gaofans.vertx.boot.web.utils.WebConstant;
import io.vertx.ext.web.Route;
import io.vertx.ext.web.handler.CSRFHandler;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author GaoFans
 */
@Configuration(proxyBeanMethods = false)
public class CsrfHandlerAutoConfig {

    @Bean
    @ConfigurationProperties(prefix = WebConstant.VERTX_WEB_CSRF_PREFIX)
    @ConditionalOnProperty(prefix = WebConstant.VERTX_WEB_CSRF_PREFIX,name = "secret" )
    public CsrfHandlerProperties csrfHandlerProperties(){
        return new CsrfHandlerProperties();
    }

    @Bean
    @ConditionalOnBean(CsrfHandlerProperties.class)
    public RouterExtConfigurer csrfHandlerExtConfigurer(CsrfHandlerProperties properties){
        return router -> {
            Route route = router.route().order(HttpHandlerOrder.CSRF_HANDLER);
            for (String s : properties.getPath()) {
                route.path(s);
            }
            route.handler(CSRFHandler
                    .create(properties.getSecret())
                    .setCookieName(properties.getCookieName())
                    .setCookiePath(properties.getCookiePath())
            .setHeaderName(properties.getHeaderName())
            .setResponseBody(properties.getResponseBody())
            .setTimeout(properties.getTimeout())
            .setNagHttps(properties.isNagHttps()));
        };
    }
}
